<template>
  <div id="SkillFollowDubList">
    <crumb />
    <div class="main">
        <div class="main_item" v-for="(item, index) in dubList" :key="index">
            <div class="main_item_itemTop">
                <div class="main_item_img">
                    <img src="@/assets/images/home_tx@2x.png" alt=""/>
                </div>
                <div class="main_item_itemTop_text">
                    <div>{{item.resource_role_name}}</div>
                    <div>{{item.resource_oral_content}}</div>
                </div>
            </div>
            <div class="main_item_itemBottom">
                <div class="main_item_itemBottom_text">
                    <div>我</div>
                    <div></div>
                </div>
                <div class="main_item_img">
                    <img src="@/assets/images/resource-icons/gl_kyxl@2x.png" @click="SoundPlay" alt=""/>
                </div>
            </div>
        </div>
    </div>
    <el-dialog
      :title="isSound?'已经连接麦克风':'请先连接到麦克风'"
      :visible.sync="dialogVisible"
      width="30%"
      center
      :close-on-press-escape='false'
      :close-on-click-modal='false'
      @close='Resetting'
      >
      <div style="text-align:center;">
        <span v-if="!isSound">并检测到麦克风已连接</span>
        <span v-if="isSound"><i class="el-icon-mic"></i></span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="!isSound" @click="retrySound">重试</el-button>
        <el-button type="primary" v-if="isSound&&!isStart" @click="startRecording">开始</el-button>
        <div>
          <el-button type="primary" v-if="isStart" @click="Resetting">重录</el-button>
          <el-button type="danger"  v-if="isStart" @click="stopRecording">提交</el-button>
        </div>
        <!-- <el-button type="primary" @click="dialogVisible = false">确 定</el-button> -->
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { speechDubsubmit, speechDub, speechUpdateDuration } from '@/api/student/training/speech'
import Recorder from 'recorder-js'
const audioContext = new (window.AudioContext || window.webkiAudioContext)()
const recorder = new Recorder(audioContext, {
  // onAnalysed: data => console.log(data)
})
// eslint-disable-next-line no-unused-vars
let isRecording = false
// eslint-disable-next-line no-unused-vars
let blobDow = null
// let isOkSound = false
// 一些浏览器部分支持 mediaDevices。我们不能直接给对象设置 getUserMedia
// 因为这样可能会覆盖已有的属性。这里我们只会在没有getUserMedia属性的时候添加它。

// if (navigator.mediaDevices.getUserMedia === undefined) {
//   navigator.mediaDevices.getUserMedia = function (constraints) {
//     // 首先，如果有getUserMedia的话，就获得它
//     var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia
//     // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
//     if (!getUserMedia) {
//       return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
//     }
//     // 否则，为老的navigator.getUserMedia方法包裹一个Promise
//     return new Promise(function (resolve, reject) {
//       getUserMedia.call(navigator, constraints, resolve, reject)
//     })
//   }
// }
navigator.mediaDevices.getUserMedia({ audio: true })
  .then(stream => recorder.init(stream))
  .catch(err => { console.log('Uh oh... unable to get stream...麦克风未连接', err) })

// eslint-disable-next-line no-unused-vars
function download () {
  Recorder.download(blobDow, 'my-audio-file')
}

export default {
  name: 'SkillFollowRead',
  components: {},
  data () {
    return {
      dialogVisible: false,
      isSound: false,
      isStart: false,
      isRecording: false,
      blob: null,
      dubList: [],
      setTimeFn: null
    }
  },
  mounted () {
    this.speechDub()
    this.speechUpdateDuration()
  },
  methods: {
    async speechDub () {
      const res = await speechDub({
        'roleId': this.$route.query.role_id,
        'resourceOralId': this.$route.query.resourceOralId
      })
      this.dubList = res.data
      console.log(res)
    },
    AudioPlay (ref, index) {
      for (const key in this.$refs) {
        if (ref === key) {
          this.$refs[key].play()
          this.$set(this.tableData[index], 'isPlayOk', true)
          // this.tableData[index].isPlayOk = true
        } else {
          this.tableData.forEach((item, indexOne) => {
            if (index !== indexOne) {
              this.$set(this.tableData[indexOne], 'isPlayOk', false)
            };
          })
          this.$refs[key].currentTime = 0
          this.$refs[key].pause()
          // this.$set(this.tableData[index], 'isPlayOk', false)
        }
        this.$refs[key].addEventListener('ended', this.PlayOk(event, key, index), false)
      }
    },
    PlayOk (eventTar, key, index) {
      return (eventAudio) => {
        this.tableData[index].isPlayOk = false
      }
    },
    AudioPause (ref, index) {
      this.$refs[ref].pause()
      this.tableData[index].isPlayOk = false
    },
    SoundPlay () {
      // 临时使用结束之后放开
      this.retrySound()
      this.dialogVisible = true
      console.log(this.isSound)
      // 临时使用
      // setTimeout(() => {
      //   this.isSound = true
      // })
    },
    retrySound () {
      navigator.mediaDevices.getUserMedia({ audio: true })
        .then(stream => { recorder.init(stream); this.isSound = true })
        .catch(err => { console.log('Uh oh... unable to get stream...麦克风未连接', err); this.isSound = false })
    },
    Submit () {},
    Resetting () {
      this.isStart = false
      recorder.stop()
    },
    startRecording () {
      recorder.start()
        .then(() => { isRecording = true; console.log('开始了'); this.isStart = true })
    },
    stopRecording () {
      recorder.stop()
      speechDubsubmit({
        lessonOralCatalogId: this.$route.query.lessonOralCatalogId,
        resourceOralId: this.$route.query.resourceOralId,
        resultJson: '',
        score: '90'
      }).then(res => {
        this.$router.push({ name: 'skillfollowdubranklist',
          query: {
            'lessonOralCatalogId': this.$route.query.lessonOralCatalogId,
            'resourceOralId': this.$route.query.resourceOralId
          } })
      })
      // recorder.stop()
      //   .then(({ blob, buffer }) => {
      //     console.log(blob, buffer)
      //     // eslint-disable-next-line no-self-assign
      //     blobDow = blob
      //     download()
      //     // buffer is an AudioBuffer
      //   })
    },
    async speechUpdateDuration () {
      await speechUpdateDuration({
        lessonOralBatchId: this.$route.query.lessonOralBatchId
      })
      this.setTimeFn = setTimeout(this.speechUpdateDuration, 8000)
    }
  },
  destroyed () {
    clearTimeout(this.setTimeFn)
  }
}
</script>

<style scoped lang="scss" >
#SkillFollowDubList{
    .main{
        &_item{
            &_img{
                border:1px solid rgba(0,0,0,.5);
                width:60px;
                height:60px;
                border-radius: 30px;
                overflow: hidden;
                >img{
                    width: 100%;
                }
            }
            &>div{
                display: flex;
                align-items: center;
                padding: 35px;
                border-bottom:1px solid rgba(0,0,0,.1);
             }
            &_itemTop{
                &_text{
                   margin-left: 20px;
                  >div:nth-child(1){
                        color: rgb(130, 130, 130);
                        font-weight: bold;
                        margin-bottom: 10px;
                     }
                    >div:nth-child(2){
                        margin-top: 10px;
                   }
                }
            }
            &_itemBottom{
                justify-content: flex-end;
                &_text{
                    text-align: right;
                    margin-right: 20px;
                    >div:nth-child(1){
                         color: rgb(130, 130, 130);
                         font-weight: bold;
                         margin-bottom: 10px;
                     }
                    >div:nth-child(2){
                        margin-top: 10px;
                   }
                }
            }
        }
    }
}
.el-dialog{
 .el-dialog__body{
    text-align:center !important;
  }
}
</style>
